<template>
  <!-- v-hasPerm="[`${searchConfig.pageName}:query`]" -->
  <div class="search-container">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <template v-for="item in searchConfig.formItems" :key="item.prop">
        <el-form-item :label="item.label" :prop="item.prop" v-show="!item.hidden">
          <!-- Select 选择器 -->
          <template v-if="item.type === 'select'">
            <el-select v-model="queryParams[item.prop]" v-bind="item.attrs">
              <template v-for="option in item.options" :key="option.value">
                <el-option :label="option.label" :value="option.value" />
              </template>
            </el-select>
          </template>
          <!-- TreeSelect 树形选择 -->
          <template v-else-if="item.type === 'tree-select'">
            <el-tree-select v-model="queryParams[item.prop]" v-bind="item.attrs" />
          </template>
          <!-- DatePicker 日期选择器 -->
          <template v-else-if="item.type === 'date-picker'">
            <el-date-picker 
              v-model="queryParams[item.prop]" 
              v-bind="item.attrs"
              :default-time="[
                new Date(2024, 1, 1, 0, 0, 0),
                new Date(2024, 2, 1, 23, 59, 59),
              ]"
              @change="handleDateChange($event, item)" />
          </template>
          <template v-else-if="item.type === 'custom'">
            <slot :name="item.slotName ?? item.prop" :prop="item.prop" v-bind="item.attrs"></slot>
          </template>
          <!-- Input 输入框 -->
          <template v-else>
            <el-input v-model="queryParams[item.prop]" v-bind="item.attrs" @keyup.enter="handleQuery"
              :placeholder="item.attrs.placeholder" />
          </template>
        </el-form-item>
      </template>
      <el-form-item v-if="isShowBtn">
        <el-button type="primary" icon="search" @click="handleQuery">
          {{$t('btn.6')}}
        </el-button>
        <el-button :icon="Refresh" @click="handleReset">{{$t('btn.7')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import moment from 'moment'
import { toISOTime } from '@/utils/common'
import { onMounted } from 'vue';
import { Refresh } from '@element-plus/icons-vue'

const props = defineProps({
  searchConfig: {
    type: Object,
    default: {
      pageName: "",
      formItems: []
    }
  },
  isShowBtn:{
    type:Boolean,
    default:true
  },
});

const { t } = useI18n();

// 自定义事件
const emit = defineEmits(['queryClick', 'resetClick'])

const queryFormRef = ref();

// 重置操作
function handleReset () {
  if (props.searchConfig.defSearch) {
    // 重置后恢复初始值
    for (const item of props.searchConfig.formItems) {
      if (item.initialValue !== undefined) {
        queryParams[item.prop] = item.initialValue;
      } else {
        queryParams[item.prop] = "";
      }
      
      // 处理时间特殊情况
      if (item.prop === 'time' && props.searchConfig.defSearch) {
        const time = new Date();
        let start = moment(time).format('YYYY-MM-DD')
        let end = moment(time).format('YYYY-MM-DD')
        queryParams[item.prop] = [start + ' 00:00:00', end + ' 23:59:59']
      }
    }
  } else {
    queryFormRef.value?.resetFields();
  }
  emit("resetClick", queryParams);
}
const setParams = (obj) => {
  Object.assign(queryParams, obj)
}
// 查询操作
function handleQuery () {
  // 如果queryParams是空字符串或undefined，则删除
  Object.keys(queryParams).forEach(key => {
    if (queryParams[key] === '' || queryParams[key] === undefined) {
      delete queryParams[key]
    }
  })
  if (queryParams.time !== undefined) {
    if (queryParams.time) {
      queryParams.start = toISOTime(queryParams.time[0])
      queryParams.end = toISOTime(queryParams.time[1])
    } else {
      queryParams.start = ''
      queryParams.end = ''
    }
  }
  // toISOTime
  emit("queryClick", queryParams, true);
}
// 获取分页数据
function getQueryParams () {
  return queryParams;
}
// 搜索表单数据
const queryParams = reactive({});

// 暴露的属性和方法
defineExpose({ getQueryParams, setParams, handleQuery });
onMounted(() => {
  for (const item of props.searchConfig.formItems) {
    item.initFn && item.initFn(item);
    queryParams[item.prop] = item.initialValue ?? "";
    if (item.prop === 'time' && props.searchConfig.defSearch) {
      const time = new Date();
      let start = moment(time).format('YYYY-MM-DD')
      let end = moment(time).format('YYYY-MM-DD')
      queryParams[item.prop] = [start + ' 00:00:00', end + ' 23:59:59']
    }
  }
})

// 处理日期选择变化
function handleDateChange(value, item) {
  console.log('item.allowCrossMonth===>',item.allowCrossMonth)
  // 如果 allowCrossMonth 为 undefined 或 null，默认允许跨月
  if (item.allowCrossMonth === false && value && value.length === 2) {
    const startMonth = moment(value[0]).month();
    const endMonth = moment(value[1]).month();
    console.log('startMonth==>',startMonth,endMonth)
    if (startMonth !== endMonth) {
      console.log('进来了')
      ElMessage.warning(t('hint.162'));
      queryParams[item.prop] = null;
    }
  }
}
</script>

<style lang="scss" scoped>
.search-container {
  padding: 18px 0 0 10px;
  margin-bottom: 10px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}
</style>
